<style type="text/css">
    div#rainbow_image_list_widget {
        border-bottom:2px solid #dcdcdc;
        margin-bottom:20px;
        padding:0 0 20px 0;
        display:none;
    }
    div#rainbow_image_list_widget ul {
        margin:0;
        padding:0;
        list-style-type:none;
    }
    div#rainbow_image_list_widget ul li {
        margin:10px 0;
        padding:10px;
        min-height:30px;
        background:url("{{ STATIC_URL }}commons/background/8f1f1_background.png") #dcdcdc;
    }

    div#rainbow_image_list_widget ul li:hover {
        box-shadow:4px 4px 4px gray;
    }

    div.rainbowImagePreview {
        width:626px;
        margin-left:40px;
    }

    div.rainbowImageWidget {
        width:300px;
        background:yellow;
    }
    div.rainbowImagePreviewWidget {
        opacity:0;
    }
    div.rainbowImageCommentWidget {
        width:286px;
        float:right;
        padding:0 0 0 20px;
    }
    div.rainbowImageCommentWidget textarea {
        width:266px;
        max-width:266px;
        min-width:266px;
        padding:10px;
        outline:none;
        border:0 solid white;
    }
    div.rainbowImageDeletedWidget {
        width:50px;
        float:right;
    }
    div.rainbowImageMoveWidget {
        width:40px;
        float:left;
    }
    div.rainbowImageMoveButton {
        display:none;
    }
    div.rainbowImageMoveButton:hover {
        cursor:move;
    }
    div.rainbowImageDeletedButton {
        margin-left:20px;
    }
    div.rainbowImageInfo {
        margin:10px;
    }
    div.rainbowImageUploadedProgressBar {
        margin:10px;
    }
</style>
<div id="rainbow_image_list_widget">
    <ul id="rainbow_image_preview_item_list">
    </ul>
</div>

<div id="rainbow_image_preview_item_tmp" style="display:none;">
    <div class="rainbowImageMoveWidget rainbowImageWidgetSize">
        <div class="rainbowImageMoveButton"></div>
    </div>
    <div class="rainbowImageDeletedWidget rainbowImageWidgetSize">
        <div class="rainbowImageDeletedButton"></div>
    </div>
    <div class="rainbowImagePreviewWidget rainbowImagePreview" style="display:none;">
        <div class="rainbowImageCommentWidget rainbowImageWidgetSize">
            <label>说点什么？</label>
            <br/><br/>
            <label>
                <textarea name="rainbow_image_comment"></textarea>
            </label>
        </div>
        <div class="rainbowImageWidget rainbowImageWidgetSize">
            <img/>
        </div>
    </div>
    <div class="rainbowImageUploadedProgressWidget rainbowImagePreview">
        <div class="rainbowImageInfo">
            <div style="float:left;font-weight:bold;width:80px;margin-right:20px;">
                <label>正在上传....</label>
            </div>
            <div style="float:left;width:260px;overflow:hidden;">
                <label class="rainbowImageFileName"></label>
            </div>
            <div style="float:left;width:170px;overflow:hidden;margin-right:20px;">
                <label class="rainbowImageFileSize"></label>
                <label>KB</label>
            </div>
            <div style="font-weight:bold;margin-left:550px;">
                <label class="rainbowImageFileUploadedRate">0</label>
                <label>%</label>
            </div>
        </div>
        <div class="rainbowImageUploadedProgressBar"></div>
    </div>
</div>

<script type="text/javascript">
    var jquery = $, jQuery;
    (function($){
        $.fn.extend({
            inputHiddenSerialization:function(options, prefix){
                var defaults = {};
                var opts = $.extend(defaults, options);
                for(var key in opts) {
                    var value = opts[key];
                    var inputHidden = $(this).find("input[name='" + prefix + "_" + key + "']");
                    if ($.isEmptyObject(inputHidden.attr("name"))) {
                        inputHidden = $("<input type='hidden'/>");
                        inputHidden.attr("name", prefix + "_" + key);
                        $(this).append(inputHidden);
                    }
                    inputHidden.val(value);
                }
            },
            inputHiddenDeserialization:function(prefix){
                var inputs = $(this).find("input[name^='" + prefix + "']");
                var values = {};
                if (!$.isEmptyObject(inputs) && !$.isEmptyObject(prefix)) {
                    for (var i=0; i<inputs.size(); i++) {
                        var input = $(inputs.get(i));
                        var name = input.attr("name");
                        if (name.length > prefix.length) {
                            name = name.substring(prefix.length + 1)
                        }
                        values[name] = input.val();
                    }
                }
                return values;
            },
            _rainbowImagePreviewAddWidget:function(options){
                var defaults = {};
                var opts = $.extend(defaults, options);
                var widget = $(this);
                var imagePreviewItemWidget = $("<li class='rainbowImagePreviewItem'/>");
                imagePreviewItemWidget.html($("div#rainbow_image_preview_item_tmp").html());
                $(this).find("ul#rainbow_image_preview_item_list").append(imagePreviewItemWidget);
                imagePreviewItemWidget.find("label.rainbowImageFileUploadedRate").text(100);
                imagePreviewItemWidget.find("div.rainbowImageUploadedProgressWidget").animate({opacity:0}, 1000, function(){
                    $(this).hide(500, function(){
                        imagePreviewItemWidget._rainbowImage(opts);
                    });
                });
                if (widget.css("display") == "none") {
                    widget.show();
                }
                //是否显示重新排序按钮
                if (widget.find(".rainbowImagePreviewItem").size() > 1) {
                    widget.find("div.rainbowImageMoveButton").show();
                }
            },
            _rainbowImage:function(options){
                var defaults = {};
                var opts = $.extend(defaults, options);
                var itemWidget = $(this);
                $(this).find("div.rainbowImageDeletedButton").click(function(){
                    var p = itemWidget.parent();
                    var itemWidgetClass = itemWidget.attr("class");
                    itemWidget.animate({opacity:0}, 2000, function(){
                        $(this).hide(500, function(){
                            $(this).remove();
                            if (p.find("." + itemWidgetClass).size() < 1) {
                                p.parent().hide();
                            }
                        });
                    });
                });
                var imgPreviewWidget = $(this).find("div.rainbowImagePreviewWidget");
                $(this).find("div.rainbowImageInfo").inputHiddenSerialization(opts, "rainbow_image_serialization");
                imgPreviewWidget.show(500, function(){
                    var imgWidget = $(this).find("div.rainbowImageWidget");
                    var img = imgWidget.find("img");
                    var w = imgWidget.width();
                    var h = w * opts.height / opts.width;
                    var css = {
                        width:w,
                        height:h
                    };
                    img.css(css);
                    img.attr("src", "/static/rainbow/images/900/" + opts.uuid + ".jpeg");
                    imgWidget.css(css);
                    var commentWidget = $(this).find("div.rainbowImageCommentWidget");
                    commentWidget.css({
                        height:h
                    });
                    commentWidget.find("textarea").css({
                        height:h - 120,
                        "min-height":h - 80,
                        "max-height":h - 80
                    });
                    $(this).animate({opacity:1}, 1000);
                });

            },
            _rainbowImagePreviewItem:function(options){
                var defaults = {};
                var opts = $.extend(defaults, options);
                var itemWidget = $(this);
                itemWidget.find("label.rainbowImageFileName").text(opts.file.name);
                itemWidget.find("label.rainbowImageFileSize").text(parseInt(opts.file.size/1024));
                var bar = itemWidget.find("div.rainbowImageUploadedProgressBar");
                bar.progressbar({
                    max:opts.file.size
                });
                //AJAX上传文件
                var xhr = new XMLHttpRequest();
                var serverForm = $("div#rainbow_image_selector").parent();
                var serverUrl = serverForm.attr("action");
                var uploadHash = hex_md5(new Date().getTime() + serverForm.find("input[name='rainbow_image_progress']").val());
                serverUrl = serverUrl + "?rainbow_image_progress=" + uploadHash + "&format=json";
                var method = serverForm.attr("method");
                xhr.open(method, serverUrl, true);
                var formData = new FormData();
                formData.append(serverForm.find("input[type='file']").attr("name"), opts.file);
                formData.append("csrfmiddlewaretoken", serverForm.find("input[name='csrfmiddlewaretoken']").val());
                xhr.send(formData);
                var progressHash = hex_md5(opts.file.name + uploadHash);
                var interval = window.setInterval(function(){
                    $.get('/rainbow/image/progress?rainbow_image_progress=' + progressHash, function(data){
                        if (!$.isEmptyObject(data)) {
                            var uploadedData = parseInt(data['uploaded_data']);
                            bar.progressbar({
                                value:uploadedData
                            });
                            itemWidget.find("label.rainbowImageFileUploadedRate").text(parseInt(uploadedData * 100/opts.file.size));
                        }
                    });
                }, 500);
                xhr.onload = function(){
                    if (200 == this.status) {
                        var response = this.response;
                        window.clearInterval(interval);
                        bar.progressbar({
                            value:opts.file.size
                        });
                        itemWidget.find("label.rainbowImageFileUploadedRate").text(100);
                        itemWidget.find("div.rainbowImageUploadedProgressWidget").animate({opacity:0}, 1000, function(){
                            $(this).hide(500, function(){
                                itemWidget._rainbowImage(JSON.parse(response));
                            });
                        });
                    } else if (404 == this.status) {
                        window.clearInterval(interval);
                    } else if (500 == this.status) {
                        window.clearInterval(interval);
                    }
                };
                itemWidget.find("div.rainbowImageDeletedButton").click(function(){
                    xhr.abort();
                    window.clearInterval(interval);
                    var p = itemWidget.parent();
                    var itemWidgetClass = itemWidget.attr("class");
                    itemWidget.remove();
                    if (p.find("." + itemWidgetClass).size() < 1) {
                        p.parent().hide();
                    }
                });
                itemWidget.find("div.rainbowImageMoveButton").mousedown(function(){
                    itemWidget.parent().sortable({
                        axis:"y",
                        disabled:false,
                        stop:function(event, ui){
                            ui.item.parent().sortable({
                                disabled:true
                            });
                        }
                    });
                });
                $(document).mouseup(function(){
                    itemWidget.parent().sortable({
                        disabled:true
                    });
                });
            },
            _rainbowImagePreviewAddItem:function(options){
                var defaults = {file:null};
                var opts = $.extend(defaults, options);
                if ($.isEmptyObject(opts.file)) {
                    return;
                }
                //检查文件类型
                var imageInput = $("div#rainbow_image_selector").find("input[type='file']");
                var allowedImageTypes = imageInput.attr("accept");
                var fileType = opts.file.type.toLowerCase();
                if (allowedImageTypes.indexOf(fileType) != -1) {
                    //检查文件大小
                    var allowedImageSize = parseInt(imageInput.attr("maxSize"));
                    if (! allowedImageSize < opts.file.size) {
                        var imagePreviewItemWidget = $("<li class='rainbowImagePreviewItem'/>");
                        imagePreviewItemWidget.html($("div#rainbow_image_preview_item_tmp").html());
                        $(this).find("ul#rainbow_image_preview_item_list").append(imagePreviewItemWidget);
                        imagePreviewItemWidget._rainbowImagePreviewItem(opts);
                        if ($(this).css("display") == "none") {
                            $(this).show();
                        }
                        //是否显示重新排序按钮
                        if ($(this).find(".rainbowImagePreviewItem").size() > 1) {
                            $(this).find("div.rainbowImageMoveButton").show();
                        }
                    }
                }
            },
            rainbowImagePreviewList:function(options){
                if (null != arguments && arguments.length > 0) {
                    var firstArg = arguments[0];
                    switch (firstArg) {
                        case "add":
                            return $(this)._rainbowImagePreviewAddItem(arguments[1]);
                            break;
                        case "addWidget":
                            $(this)._rainbowImagePreviewAddWidget(arguments[1]);
                            break;
                        default:
                            break;
                    }
                }
                var defaults = {};
                var opts = $.extend(defaults, options);
                return null;
            }
        });
    })(jquery);

    $(document).ready(function(){
        $(document).kjsuiLoad("button");
        $(document).kjsuiLoad("uploadWidget");
        $(document).kjsuiLoad("md5");
        $("div.rainbowImageDeletedButton").kjsuiCloseButton({size:20});
        var rainbowImageMoveButton = $("div.rainbowImageMoveButton");
        rainbowImageMoveButton.kjsuiMoveButton({width:15, height:20});

        $("div.rainbowImageUploadedProgressBar").progressbar({
            value:0
        });

        $("div#rainbow_image_list_widget").rainbowImagePreviewList();
    });
</script>